//
//  SVVideoEditViewController.m
//  ShortVideo-ccinon
//
//  Created by LIN TONG on 2017/6/28.
//  Copyright © 2017年 LIN TONG. All rights reserved.
//

#import "SVVideoEditViewController.h"
#import "SVConfig.h"
#import "SVVideo.h"
#import "SVNavigationBar.h"
#import "SVQRCode.h"
#import "SVTextEditViewController.h"
#import "SVTextView.h"
#import "SVAPIReqeust.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "WCLRecordEngine.h"
#import "WMPlayer.h"
#import <Masonry.h>
#import "SVUploadProgressView.h"

@interface SVVideoEditViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,WMPlayerDelegate>{
    UIButton *playButton;
    UIButton *reuploadButton;
    UITableView *contentTable;
    
    NSMutableArray *titles;
    NSMutableArray *placeHolders;
    NSMutableArray *values;
    
    UIImageView *videoBackground;
    
    WCLRecordEngine *recordEngine;
    
    WMPlayer    *wmPlayer;
    BOOL        changedVideo;
}

@end

@implementation SVVideoEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    titles = [NSMutableArray arrayWithArray:@[@[@"品牌"],@[@"标题",@"简介"]]];
    placeHolders = [NSMutableArray arrayWithArray:@[@[@"您的品牌"],@[@"二维码标题",@"二维码简介"]]];
    values = [NSMutableArray array];
    
    NSMutableArray *qrValues = [NSMutableArray arrayWithObjects:@"",@"", nil];
    if(self.video.name && self.video.name.length){
        [qrValues replaceObjectAtIndex:0 withObject:self.video.name];
    }
    if(self.video.des && self.video.des.length){
        [qrValues replaceObjectAtIndex:1 withObject:self.video.des];
    }
    
    NSMutableArray *brandValues = [NSMutableArray arrayWithObjects:@"", nil];
    if(self.qrcode.companyBrand && self.qrcode.companyBrand.length){
        [brandValues replaceObjectAtIndex:0 withObject:self.qrcode.companyBrand];
    }
    [values addObject:brandValues];
    [values addObject:qrValues];
    
    // Do any additional setup after loading the view.
    SVNavigationBar *naviBar = [[SVNavigationBar alloc]init];
    [naviBar setBackHander:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [naviBar setDoneHandler:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [naviBar setTitle:@"编辑视频"];
    naviBar.showBackButton = YES;
    naviBar.hidenAccountButton = YES;
    [self.view addSubview:naviBar];
    
    videoBackground = [[UIImageView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(naviBar.frame), __SCREEN_WIDTH__, S(180))];
    videoBackground.contentMode = UIViewContentModeScaleAspectFit;
    videoBackground.userInteractionEnabled = YES;
    videoBackground.backgroundColor = UIColorMake(100, 100, 100, 1);
    [self.view addSubview:videoBackground];
    
    playButton = [[UIButton alloc]initWithFrame:CGRectMake(S(138), S(53), S(44), S(44))];
    [playButton setBackgroundImage:[UIImage imageNamed:@"icon_play_btn"] forState:UIControlStateNormal];
    [playButton addTarget:self action:@selector(clickToPlay:) forControlEvents:UIControlEventTouchUpInside];
    [videoBackground addSubview:playButton];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        UIImage *image = [SVCommon thumbnailImageForVideo:[NSURL URLWithString:self.video.url]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [videoBackground setImage:image];
        });
    });
    
    reuploadButton = [[UIButton alloc]initWithFrame:CGRectMake(S(112), CGRectGetMaxY(playButton.frame)+S(27), S(89), S(22))];
    reuploadButton.center = CGPointMake(__SCREEN_WIDTH__/2.0, reuploadButton.center.y);
    [reuploadButton setBackgroundImage:[UIImage imageNamed:@"reupload_btn"] forState:UIControlStateNormal];
    [reuploadButton addTarget:self action:@selector(uploadVideo:) forControlEvents:UIControlEventTouchUpInside];
    [videoBackground addSubview:reuploadButton];
    
    contentTable = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(videoBackground.frame), __SCREEN_WIDTH__, __SCREEN_HEIGHT__-CGRectGetMaxY(videoBackground.frame)) style:UITableViewStyleGrouped];
    contentTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    contentTable.dataSource = self;
    contentTable.delegate = self;
    contentTable.scrollEnabled = NO;
    [self.view addSubview:contentTable];
    [contentTable reloadData];
    
    UIButton *saveButton = [[UIButton alloc]initWithFrame:CGRectMake(S(20), __SCREEN_HEIGHT__-S(52)-S(44), S(280), S(44))];
    saveButton.backgroundColor = UIColorMake(249, 80, 0, 1);
    saveButton.layer.cornerRadius = S(5);
    saveButton.layer.masksToBounds = YES;
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(clickSaveButton:) forControlEvents:UIControlEventTouchUpInside];
    saveButton.titleLabel.font = FontM(17);
    [self.view addSubview:saveButton];
    
    UILabel *copyright = [[UILabel alloc]initWithFrame:CGRectMake(0, __SCREEN_HEIGHT__-S(7)-S(15), __SCREEN_WIDTH__, S(15))];
    copyright.textAlignment = NSTextAlignmentCenter;
    copyright.font = Font(12);
    copyright.textColor = UIColorMake(249, 74, 0, 1);
    copyright.text = @"copyright@ccinon";
    [self.view addSubview:copyright];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if(wmPlayer){
        [self releaseWMPlayer];
    }
}

- (void)clickToPlay:(UIButton *)sender{
    if(self.video.url && self.video.url.length){
        
        if(wmPlayer){
            [self releaseWMPlayer];
        }
        wmPlayer = [[WMPlayer alloc]init];
        wmPlayer.delegate = self;
        wmPlayer.closeBtnStyle = CloseBtnStyleClose;
        wmPlayer.URLString = self.video.url;
        wmPlayer.titleLabel.text = self.video.name;
        wmPlayer.isFullscreen = NO;
        
        wmPlayer.frame = videoBackground.frame;
        
        [self.view addSubview:wmPlayer];
        
        [wmPlayer play];
    }
}

- (void)clickSaveButton:(UIButton *)sender{
    if(self.state == SV_VIDEO_NEW){
        if(self.video.url){
            
            SVUploadProgressView *progressView = [[SVUploadProgressView alloc]init];
            [progressView show];
            
            [progressView setDescription:@"正在转码,请稍后..."];
            
            recordEngine = [[WCLRecordEngine alloc] init];
            [recordEngine changeMovToMp4: [NSURL URLWithString:self.video.url] dataBlock: ^(UIImage *movieImage) {
                NSFileManager *fm = [NSFileManager defaultManager];
                unsigned long long fileSize = [[fm attributesOfItemAtPath:recordEngine.videoPath error:nil]fileSize];
                [progressView setDescription:@"正在上传..."];
                
                [SVCommon uploadVideoInPath:recordEngine.videoPath qrID:self.qrcode.ID updateProgress:^(float progress) {
                    int num = progress*100;
                    [progressView setDescription:[NSString stringWithFormat:@"正在上传%d%%...",num]];
                    [progressView setProgressValue:progress];
                    [progressView setNeedsDisplay];
                } completionBlock:^(BOOL success,NSString *objectKey,NSString *endPoint,NSString *buketName) {
                    if(success){
                        [progressView setDescription:@"正在同步..."];
                        
                        self.video.url = [NSString stringWithFormat:@"http://%@.%@/%@",buketName,endPoint,objectKey];
                        self.video.fileSize = fileSize;
                        
                        NSString *descr = values[1][1];
                        NSString *title = values[1][0];
                        
                        [SVAPIReqeust svRequestAPI:API(@"/mct/vod/video/add") method:@"POST" parametors:@{@"vod_qr_id":[NSString stringWithFormat:@"%ld",self.qrcode.ID],@"vod_video_path":self.video.url,@"vod_video_size":[NSString stringWithFormat:@"%lld",self.video.fileSize],@"vod_video_title":title,@"vod_video_describe":descr} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
                            [progressView close];
                            if(success){
                                [self.navigationController popViewControllerAnimated:YES];
                            }
                        }];
                        
                    }
                }];
                
            }];
        }
    }else{
        
        //修改视频的情况下重新上传视频到oss，未修改则不需要重新上传
        if(changedVideo){
            SVUploadProgressView *progressView = [[SVUploadProgressView alloc]init];
            [progressView show];
            
            [progressView setDescription:@"正在转码,请稍后..."];
            
            recordEngine = [[WCLRecordEngine alloc] init];
            [recordEngine changeMovToMp4: [NSURL URLWithString:self.video.url] dataBlock: ^(UIImage *movieImage) {
                NSFileManager *fm = [NSFileManager defaultManager];
                unsigned long long fileSize = [[fm attributesOfItemAtPath:recordEngine.videoPath error:nil]fileSize];
                [progressView setDescription:@"正在上传..."];
                
                [SVCommon uploadVideoInPath:recordEngine.videoPath qrID:self.qrcode.ID updateProgress:^(float progress) {
                    int num = progress*100;
                    [progressView setDescription:[NSString stringWithFormat:@"正在上传%d%%...",num]];
                    [progressView setProgressValue:progress];
                    [progressView setNeedsDisplay];
                } completionBlock:^(BOOL success,NSString *objectKey,NSString *endPoint,NSString *buketName) {
                    if(success){
                        [progressView close];
                        self.video.url = [NSString stringWithFormat:@"http://%@.%@/%@",buketName,endPoint,objectKey];
                        self.video.fileSize = fileSize;
                        
                        NSString *descr = values[1][1];
                        NSString *title = values[1][0];
                        
                        [SVAPIReqeust svRequestAPI:API(@"/mct/vod/video/edt") method:@"POST" parametors:@{@"vod_qr_id":@(self.qrcode.ID),@"vod_video_id":[NSString stringWithFormat:@"%ld",self.video.videoID],@"vod_video_title":title,@"vod_video_describe":descr,@"vod_video_path":self.video.url,@"vod_video_size":@(self.video.fileSize)} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
                            if(success){
                                [self.navigationController popViewControllerAnimated:YES];
                            }
                        }];
                    }
                }];
                
            }];
        }else{
            NSString *descr = values[1][1];
            NSString *title = values[1][0];
            
            [SVAPIReqeust svRequestAPI:API(@"/mct/vod/video/edt") method:@"POST" parametors:@{@"vod_qr_id":@(self.qrcode.ID),@"vod_video_id":[NSString stringWithFormat:@"%ld",self.video.videoID],@"vod_video_title":title,@"vod_video_describe":descr,@"vod_video_path":self.video.url,@"vod_video_size":@(self.video.fileSize)} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
                if(success){
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }];
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)uploadVideo:(UIButton *)sender{
    UIImagePickerController *moviePicker = [[UIImagePickerController alloc] init];
    moviePicker.delegate = self;
    moviePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    moviePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
    [self presentViewController:moviePicker animated:YES completion:^{
        
    }];
}

-(void)releaseWMPlayer{
    //堵塞主线程
    //    [wmPlayer.player.currentItem cancelPendingSeeks];
    //    [wmPlayer.player.currentItem.asset cancelLoading];
    [wmPlayer pause];
    
    
    [wmPlayer removeFromSuperview];
    [wmPlayer.playerLayer removeFromSuperlayer];
    [wmPlayer.player replaceCurrentItemWithPlayerItem:nil];
    wmPlayer.player = nil;
    wmPlayer.currentItem = nil;
    //释放定时器，否侧不会调用WMPlayer中的dealloc方法
    [wmPlayer.autoDismissTimer invalidate];
    wmPlayer.autoDismissTimer = nil;
    
    wmPlayer.playOrPauseBtn = nil;
    wmPlayer.playerLayer = nil;
    wmPlayer = nil;
}

- (void)changeToOrientation:(UIInterfaceOrientation)orientation{
    UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if(orientation == UIInterfaceOrientationPortrait && wmPlayer.isFullscreen){
        [wmPlayer removeFromSuperview];
        [videoBackground addSubview:wmPlayer];
        
        [wmPlayer mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(videoBackground).with.offset(0);
            make.left.equalTo(videoBackground).with.offset(0);
            make.right.equalTo(videoBackground).with.offset(0);
            make.height.equalTo(@(videoBackground.frame.size.height));
        }];
        
        [UIView beginAnimations:nil context:nil];
        //更改了状态条的方向,但是设备方向UIInterfaceOrientation还是正方向的,这就要设置给你播放视频的视图的方向设置旋转
        //给你的播放视频的view视图设置旋转
        wmPlayer.transform = CGAffineTransformIdentity;
        [UIView setAnimationDuration:1.0];
        //开始旋转
        [UIView commitAnimations];
        
        wmPlayer.isFullscreen = NO;
        wmPlayer.closeBtnStyle = CloseBtnStyleClose;
    }else{
        if(currentOrientation == UIInterfaceOrientationPortrait){
            [wmPlayer removeFromSuperview];
            [[UIApplication sharedApplication].keyWindow addSubview:wmPlayer];
            [wmPlayer mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(@([UIScreen mainScreen].bounds.size.height));
                make.height.equalTo(@([UIScreen mainScreen].bounds.size.width));
                make.center.equalTo(wmPlayer.superview);
            }];
            
            
            [UIView beginAnimations:nil context:nil];
            //更改了状态条的方向,但是设备方向UIInterfaceOrientation还是正方向的,这就要设置给你播放视频的视图的方向设置旋转
            //给你的播放视频的view视图设置旋转
            wmPlayer.transform = CGAffineTransformIdentity;
            wmPlayer.transform = CGAffineTransformMakeRotation(M_PI_2);
            [UIView setAnimationDuration:1.0];
            //开始旋转
            [UIView commitAnimations];
            
            wmPlayer.isFullscreen = YES;
            wmPlayer.closeBtnStyle = CloseBtnStylePop;
        }
    }
    [self setNeedsStatusBarAppearanceUpdate];
}

- (BOOL)shouldAutorotate{
    return NO;
}

-(BOOL)prefersStatusBarHidden
{
    if(wmPlayer && wmPlayer.isFullscreen){
        return YES;
    }
    return NO;
}

#pragma mark - table view delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *sectionDatas = titles[section];
    return  sectionDatas.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return titles.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return S(41);
    }else if(indexPath.section == 1){
        if(indexPath.row == 0){
            return S(41);
        }else{
            return S(100);
        }
    }
    return S(41);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        return S(12);
    }else if(section == 1){
        return S(9);
    }else{
        return S(115);
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = [NSString stringWithFormat:@"identifier%ld",indexPath.section];
    
    CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell){
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIView *horline1 = [[UIView alloc]initWithFrame:CGRectMake(0, -1, __SCREEN_WIDTH__, 1)];
        horline1.backgroundColor = UIColorMake(191, 191, 191, 1);
        [cell addSubview:horline1];
        
        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(S(13), S(12.5), S(37), S(16))];
        title.textColor = UIColorMake(160, 160, 160, 1);
        [title setFont:FontM(16)];
        title.tag = 1001;
        [cell addSubview:title];
        
        SVTextView *videoName = [[SVTextView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(title.frame)+S(10), S(4), S(230), cellHeight-S(4))];
        videoName.textColor = UIColorMake(30, 30, 30, 1);
        [videoName setFont:Font(13)];
        videoName.tag = 1002;
        videoName.editable = NO;
        [cell addSubview:videoName];
        
        UIImageView *icon = [[UIImageView alloc]initWithFrame:CGRectMake(S(294), 0, S(11), S(18))];
        icon.image = [UIImage imageNamed:@"icon_arrow"];
        icon.center = CGPointMake(icon.center.x, cellHeight/2.0);
        [cell addSubview:icon];
        
        UIView *horline = [[UIView alloc]initWithFrame:CGRectMake(0, cellHeight-1, __SCREEN_WIDTH__, 1)];
        horline.backgroundColor = UIColorMake(191, 191, 191, 1);
        [cell addSubview:horline];
    }
    
    UILabel *title = [cell viewWithTag:1001];
    UITextView *placeHolder = [cell viewWithTag:1002];
    
    title.text = titles[indexPath.section][indexPath.row];
    placeHolder.text = placeHolders[indexPath.section][indexPath.row];
    
    NSString *value = values[indexPath.section][indexPath.row];
    if(value.length > 0){
        placeHolder.text = value;
        placeHolder.textColor = UIColorMake(30, 30, 30, 1);
    }else{
        placeHolder.textColor = UIColorMake(219, 219, 219, 1);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;{
    SVTextEditViewController *textEdit = [[SVTextEditViewController alloc]init];
    textEdit.text = values[indexPath.section][indexPath.row];
    [textEdit setDoneHandler:^(NSString *result){
        if(result.length > 0){
            NSArray *oldValues = values[indexPath.section];
            NSMutableArray *newValues = [NSMutableArray array];
            for (int i=0;i<oldValues.count;i++){
                if(i == indexPath.row){
                    [newValues addObject:result];
                }else{
                    [newValues addObject:oldValues[i]];
                }
            }
            [values replaceObjectAtIndex:indexPath.section withObject:newValues];
        }
        [contentTable reloadData];
    }];
    [self.navigationController pushViewController:textEdit animated:YES];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeMovie]){
        //获取视频的名称
        NSString *videoPath   = [NSString stringWithFormat:@"%@", [info objectForKey:UIImagePickerControllerMediaURL]];
        NSRange range         = [videoPath rangeOfString: @"trim."];//匹配得到的下标
        NSString *content     = [videoPath substringFromIndex: range.location + range.length];
        
        //视频的后缀
        NSRange rangeSuffix   = [content rangeOfString: @"."];
        NSString *suffixName  = [content substringFromIndex: rangeSuffix.location + rangeSuffix.length];
        if ([suffixName isEqualToString: @"MOV"]){
            NSURL *videoUrl = [info objectForKey: UIImagePickerControllerMediaURL];
            
            changedVideo = YES;
            
            self.video.url = [videoUrl absoluteString];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                UIImage *image = [SVCommon thumbnailImageForVideo:[NSURL URLWithString:self.video.url]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [videoBackground setImage:image];
                });
            });
        }
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - WMPlayerDelegate

-(void)wmplayer:(WMPlayer *)wmplayer clickedPlayOrPauseButton:(UIButton *)playOrPauseBtn{
    
}

-(void)wmplayer:(WMPlayer *)wmplayer clickedCloseButton:(UIButton *)closeBtn{
    if(wmPlayer.isFullscreen){
        [self changeToOrientation:UIInterfaceOrientationPortrait];
        wmPlayer.fullScreenBtn.selected = wmPlayer.isFullscreen;
    }else{
        [self releaseWMPlayer];
    }
}

-(void)wmplayer:(WMPlayer *)wmplayer clickedFullScreenButton:(UIButton *)fullScreenBtn{
    if(wmPlayer.isFullscreen){
        [self changeToOrientation:UIInterfaceOrientationPortrait];
    }else{
        [self changeToOrientation:UIInterfaceOrientationLandscapeLeft];
    }
    wmPlayer.fullScreenBtn.selected = wmPlayer.isFullscreen;
}

-(void)wmplayerFinishedPlay:(WMPlayer *)wmplayer{
    
}

@end
